<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 支付订单信息
const orderInfo = ref({
  orderNumber: 'ORD' + Math.floor(100000 + Math.random() * 900000),
  orderDate: new Date().toLocaleDateString(),
  totalAmount: 299.99,
  items: [
    {
      name: '量子纠缠耳机',
      quantity: 1,
      price: 249.99
    },
    {
      name: '星际物流加急费',
      quantity: 1,
      price: 50.00
    }
  ]
})

// 支付方式
const paymentMethods = ref([
  { id: 'wechat', name: '微信支付', icon: '💬', selected: true },
  { id: 'alipay', name: '支付宝', icon: '🧧', selected: false },
  { id: 'creditcard', name: '信用卡', icon: '💳', selected: false },
  { id: 'crypto', name: '加密货币', icon: '🔐', selected: false }
])

// 信用卡信息
const cardInfo = reactive({
  number: '',
  name: '',
  expiry: '',
  cvc: ''
})

// 支付流程状态
const paymentStatus = ref('form') // form, processing, success, error

// 错误信息
const errors = reactive({})

// 选择支付方式
const selectPaymentMethod = (methodId) => {
  paymentMethods.value.forEach(method => {
    method.selected = method.id === methodId
  })
}

// 格式化信用卡号
const formatCardNumber = (value) => {
  // 移除非数字字符
  const v = value.replace(/\D/g, '').slice(0, 16)
  // 每4位添加空格
  const matches = v.match(/\d{4,16}/g)
  const match = matches && matches[0] || ''
  const parts = []
  
  for (let i = 0, len = match.length; i < len; i += 4) {
    parts.push(match.substring(i, i + 4))
  }
  
  if (parts.length) {
    return parts.join(' ')
  } else {
    return value
  }
}

// 格式化有效期
const formatExpiry = (value) => {
  // 移除非数字字符
  const v = value.replace(/\D/g, '').slice(0, 4)
  // 添加斜杠
  if (v.length > 2) {
    return v.slice(0, 2) + '/' + v.slice(2, 4)
  }
  return v
}

// 验证表单
const validateForm = () => {
  let isValid = true
  // 清空错误对象
  Object.keys(errors).forEach(key => delete errors[key])
  
  // 如果选择信用卡，验证信用卡信息
  const selectedMethod = paymentMethods.value.find(m => m.selected)
  if (selectedMethod.id === 'creditcard') {
    if (!cardInfo.number.replace(/\s/g, '')) {
      errors.cardNumber = '请输入信用卡号'
      isValid = false
    } else if (cardInfo.number.replace(/\s/g, '').length !== 16) {
      errors.cardNumber = '信用卡号应为16位数字'
      isValid = false
    }
    
    if (!cardInfo.name) {
      errors.cardName = '请输入持卡人姓名'
      isValid = false
    }
    
    if (!cardInfo.expiry) {
      errors.cardExpiry = '请输入有效期'
      isValid = false
    } else if (!/^(0[1-9]|1[0-2])\/?([0-9]{2})$/.test(cardInfo.expiry.replace(/\s/g, ''))) {
      errors.cardExpiry = '请输入有效的有效期格式(MM/YY)'
      isValid = false
    }
    
    if (!cardInfo.cvc) {
      errors.cardCvc = '请输入安全码'
      isValid = false
    } else if (!/^\d{3,4}$/.test(cardInfo.cvc)) {
      errors.cardCvc = '安全码应为3或4位数字'
      isValid = false
    }
  }
  
  return isValid
}

// 处理支付
const processPayment = () => {
  if (!validateForm()) {
    return
  }
  
  // 显示处理中状态
  paymentStatus.value = 'processing'
  
  // 模拟支付处理
  setTimeout(() => {
    // 随机模拟成功或失败（实际项目中应该调用真实的支付API）
    const isSuccess = Math.random() > 0.2
    
    if (isSuccess) {
      paymentStatus.value = 'success'
    } else {
      paymentStatus.value = 'error'
      errors.general = '支付处理失败，请稍后重试或选择其他支付方式'
    }
  }, 2000)
}

// 重新尝试支付
const retryPayment = () => {
  paymentStatus.value = 'form'
  // 清空错误对象
  Object.keys(errors).forEach(key => delete errors[key])
}

// 返回商城
const returnToMall = () => {
  router.push('/mall')
}
</script>

<template>
  <div class="payment-container">
    <h1 class="payment-title">安全支付</h1>
    
    <!-- 支付表单状态 -->
    <div v-if="paymentStatus === 'form'" class="payment-form-wrapper">
      <!-- 订单信息卡片 -->
      <div class="order-info-card">
        <h2 class="section-title">订单信息</h2>
        <div class="order-details">
          <div class="order-row">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderInfo.orderNumber }}</span>
          </div>
          <div class="order-row">
            <span class="label">订单日期：</span>
            <span class="value">{{ orderInfo.orderDate }}</span>
          </div>
          <div class="order-items">
            <h3>商品明细</h3>
            <div v-for="item in orderInfo.items" :key="item.name" class="item-row">
              <span class="item-name">{{ item.name }}</span>
              <span class="item-quantity">x{{ item.quantity }}</span>
              <span class="item-price">¥{{ item.price.toFixed(2) }}</span>
            </div>
          </div>
          <div class="total-row">
            <span class="total-label">订单总额：</span>
            <span class="total-amount">¥{{ orderInfo.totalAmount.toFixed(2) }}</span>
          </div>
        </div>
      </div>
      
      <!-- 支付方式选择 -->
      <div class="payment-methods">
        <h2 class="section-title">选择支付方式</h2>
        <div class="methods-grid">
          <div
            v-for="method in paymentMethods"
            :key="method.id"
            @click="selectPaymentMethod(method.id)"
            :class="['method-item', { selected: method.selected }]"
          >
            <span class="method-icon">{{ method.icon }}</span>
            <span class="method-name">{{ method.name }}</span>
            <span v-if="method.selected" class="selected-indicator">✓</span>
          </div>
        </div>
        
        <!-- 信用卡表单 -->
        <div v-if="paymentMethods.find(m => m.id === 'creditcard').selected" class="credit-card-form">
          <h3>信用卡信息</h3>
          <div class="form-group">
            <label for="cardNumber">卡号</label>
            <input
              id="cardNumber"
              v-model="cardInfo.number"
              type="text"
              placeholder="**** **** **** ****"
              @input="cardInfo.number = formatCardNumber($event.target.value)"
            >
            <span v-if="errors.cardNumber" class="error-message">{{ errors.cardNumber }}</span>
          </div>
          <div class="form-group">
            <label for="cardName">持卡人</label>
            <input
              id="cardName"
              v-model="cardInfo.name"
              type="text"
              placeholder="输入持卡人姓名"
            >
            <span v-if="errors.cardName" class="error-message">{{ errors.cardName }}</span>
          </div>
          <div class="form-row">
            <div class="form-group half">
              <label for="cardExpiry">有效期</label>
              <input
                id="cardExpiry"
                v-model="cardInfo.expiry"
                type="text"
                placeholder="MM/YY"
                @input="cardInfo.expiry = formatExpiry($event.target.value)"
              >
              <span v-if="errors.cardExpiry" class="error-message">{{ errors.cardExpiry }}</span>
            </div>
            <div class="form-group half">
              <label for="cardCvc">安全码</label>
              <input
                id="cardCvc"
                v-model="cardInfo.cvc"
                type="password"
                placeholder="CVC"
                maxlength="4"
              >
              <span v-if="errors.cardCvc" class="error-message">{{ errors.cardCvc }}</span>
            </div>
          </div>
        </div>
        
        <!-- 错误信息 -->
        <div v-if="errors.general" class="general-error">{{ errors.general }}</div>
        
        <!-- 提交按钮 -->
        <button class="pay-button" @click="processPayment">
          确认支付 ¥{{ orderInfo.totalAmount.toFixed(2) }}
        </button>
      </div>
    </div>
    
    <!-- 处理中状态 -->
    <div v-else-if="paymentStatus === 'processing'" class="payment-processing">
      <div class="loading-spinner"></div>
      <h2>正在处理支付...</h2>
      <p>请不要关闭页面，正在连接支付网关...</p>
    </div>
    
    <!-- 支付成功状态 -->
    <div v-else-if="paymentStatus === 'success'" class="payment-success">
      <div class="success-icon">✓</div>
      <h2>支付成功！</h2>
      <p>您的订单已支付完成，感谢您的购买。</p>
      <div class="success-details">
        <p><strong>订单编号：</strong>{{ orderInfo.orderNumber }}</p>
        <p><strong>支付金额：</strong>¥{{ orderInfo.totalAmount.toFixed(2) }}</p>
      </div>
      <button class="return-button" @click="returnToMall">
        返回商城
      </button>
    </div>
    
    <!-- 支付失败状态 -->
    <div v-else-if="paymentStatus === 'error'" class="payment-error">
      <div class="error-icon">✗</div>
      <h2>支付失败</h2>
      <p v-if="errors.general">{{ errors.general }}</p>
      <p v-else>支付处理过程中遇到问题，请稍后重试。</p>
      <div class="error-buttons">
        <button class="retry-button" @click="retryPayment">
          重新尝试
        </button>
        <button class="return-button" @click="returnToMall">
          返回商城
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 基础样式 */
.payment-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.payment-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 2rem;
  font-size: 2.5rem;
}

/* 支付表单容器 */
.payment-form-wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 2rem;
  margin-bottom: 2rem;
}

@media (max-width: 768px) {
  .payment-form-wrapper {
    grid-template-columns: 1fr;
  }
}

/* 订单信息卡片 */
.order-info-card {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  border: 1px solid #eaeaea;
}

.section-title {
  color: #333;
  margin-bottom: 1.5rem;
  font-size: 1.5rem;
  font-weight: 600;
  border-bottom: 2px solid #3498db;
  padding-bottom: 0.5rem;
}

.order-details {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.order-row {
  display: flex;
  justify-content: space-between;
  padding: 0.5rem 0;
}

.label {
  color: #666;
  font-weight: 500;
}

.value {
  color: #333;
  font-weight: 600;
}

.order-items {
  margin: 1rem 0;
}

.order-items h3 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.2rem;
}

.item-row {
  display: flex;
  justify-content: space-between;
  padding: 0.8rem 0;
  border-bottom: 1px dashed #eee;
}

.item-name {
  flex: 1;
  color: #333;
}

.item-quantity {
  color: #666;
  margin: 0 1rem;
}

.item-price {
  font-weight: 600;
  color: #333;
}

.total-row {
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 2px solid #eee;
}

.total-label {
  font-size: 1.2rem;
  font-weight: 600;
  color: #333;
}

.total-amount {
  font-size: 1.5rem;
  font-weight: 700;
  color: #e74c3c;
}

/* 支付方式选择 */
.payment-methods {
  background: white;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  border: 1px solid #eaeaea;
}

.methods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
  margin-bottom: 2rem;
}

.method-item {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  padding: 1.5rem;
  border: 2px solid #eaeaea;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.method-item:hover {
  border-color: #3498db;
  background-color: #f8f9fa;
}

.method-item.selected {
  border-color: #3498db;
  background-color: #e3f2fd;
}

.method-icon {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
}

.method-name {
  color: #333;
  font-weight: 500;
}

.selected-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  background-color: #3498db;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 0.8rem;
}

/* 信用卡表单 */
.credit-card-form {
  margin-top: 2rem;
  padding-top: 2rem;
  border-top: 1px solid #eee;
}

.credit-card-form h3 {
  color: #333;
  margin-bottom: 1.5rem;
  font-size: 1.2rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  color: #333;
  font-weight: 500;
}

.form-group input {
  width: 100%;
  padding: 0.8rem;
  border: 2px solid #ddd;
  border-radius: 6px;
  font-size: 1rem;
  transition: border-color 0.3s ease;
}

.form-group input:focus {
  outline: none;
  border-color: #3498db;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group.half {
  margin-bottom: 0;
}

.error-message {
  color: #e74c3c;
  font-size: 0.85rem;
  margin-top: 0.3rem;
  display: block;
}

.general-error {
  background-color: #fee;
  color: #e74c3c;
  padding: 1rem;
  border-radius: 6px;
  margin-bottom: 1.5rem;
  text-align: center;
}

/* 按钮样式 */
.pay-button {
  width: 100%;
  padding: 1rem;
  background-color: #2ecc71;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 1.2rem;
  font-weight: 600;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.pay-button:hover {
  background-color: #27ae60;
}

.pay-button:active {
  transform: translateY(1px);
}

/* 处理中状态 */
.payment-processing {
  text-align: center;
  padding: 4rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 2rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.payment-processing h2 {
  color: #333;
  margin-bottom: 1rem;
}

.payment-processing p {
  color: #666;
  font-size: 1.1rem;
}

/* 支付成功状态 */
.payment-success {
  text-align: center;
  padding: 4rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.success-icon {
  width: 80px;
  height: 80px;
  background-color: #2ecc71;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  margin: 0 auto 2rem;
}

.payment-success h2 {
  color: #2ecc71;
  margin-bottom: 1rem;
  font-size: 2rem;
}

.payment-success p {
  color: #666;
  font-size: 1.1rem;
  margin-bottom: 2rem;
}

.success-details {
  background-color: #f8f9fa;
  padding: 1.5rem;
  border-radius: 8px;
  margin-bottom: 2rem;
  text-align: left;
  display: inline-block;
}

.success-details p {
  margin-bottom: 0.5rem;
}

/* 支付失败状态 */
.payment-error {
  text-align: center;
  padding: 4rem;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
}

.error-icon {
  width: 80px;
  height: 80px;
  background-color: #e74c3c;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2.5rem;
  margin: 0 auto 2rem;
}

.payment-error h2 {
  color: #e74c3c;
  margin-bottom: 1rem;
  font-size: 2rem;
}

.payment-error p {
  color: #666;
  font-size: 1.1rem;
  margin-bottom: 2rem;
}

.error-buttons {
  display: flex;
  gap: 1rem;
  justify-content: center;
}

/* 通用按钮样式 */
.return-button,
.retry-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.return-button {
  background-color: #3498db;
  color: white;
}

.return-button:hover {
  background-color: #2980b9;
}

.retry-button {
  background-color: #f39c12;
  color: white;
}

.retry-button:hover {
  background-color: #e67e22;
}
</style>